<template>
  <div class="app-container">
    <el-form ref="maConfigFormRef" :model="form" :rules="rules" label-width="180px">
      <el-form-item label="微信小程序ID" prop="appid">
        <el-input v-model="form.appid" placeholder="请输入微信小程序ID"/>
      </el-form-item>
      <el-form-item label="微信小程序密钥" prop="secret">
        <el-input v-model="form.secret" placeholder="请输入微信小程序密钥"/>
      </el-form-item>
      <el-form-item label="微信小程序令牌" prop="token">
        <el-input v-model="form.token" placeholder="请输入微信小程序令牌"/>
      </el-form-item>
      <el-form-item label="微信小程序消息加密密钥" prop="aesKey">
        <el-input v-model="form.aesKey" placeholder="请输入微信小程序消息加密密钥"/>
      </el-form-item>
      <el-form-item label="微信小程序消息数据格式" prop="msgDataFormat">
        <el-radio-group v-model="form.msgDataFormat">
          <el-radio label="XML">XML</el-radio>
          <el-radio label="JSON">JSON</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-button :loading="buttonLoading" type="primary" @click="submitForm">保存</el-button>
  </div>
</template>

<script setup name="Message" lang="ts">
import {addMaConfig, getTenantMaConfig, updateMaConfig} from '@/api/infra/maConfig';
import {MaConfigForm, MaConfigQuery} from '@/api/infra/maConfig/types';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);

const maConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MaConfigForm = {
  configId: undefined,
  appid: undefined,
  secret: undefined,
  token: undefined,
  aesKey: undefined,
  msgDataFormat: 'XML',
}
const data = reactive<PageData<MaConfigForm, MaConfigQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appid: undefined,
    params: {}
  },
  rules: {
    configId: [
      {required: true, message: "配置id不能为空", trigger: "blur"}
    ],
    appid: [
      {required: true, message: "appid不能为空", trigger: "change"}
    ],
    secret: [
      {required: true, message: "secret不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

const init = async () => {
  const res = await getTenantMaConfig();
  Object.assign(form.value, res.data);
}

/** 提交按钮 */
const submitForm = () => {
  maConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.configId) {
        await updateMaConfig(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addMaConfig(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
    }
  });
}

onMounted(() => {
  init()
});
</script>
